#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <QIcon>
#include <QtConcurrent>
#include <QRandomGenerator>
#include <QScreen>
#include <QMessageBox>
#include <QKeyEvent>
#include <QDir>
#include <QSettings>
#include <QFileDialog>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    this->setWindowIcon(QIcon(":/images/logo.svg"));
    ui->getBackgroundFromOnline->setChecked(true);
    ui->debug1->hide();
    ui->debug2->hide();
    //ui->systemTime->setDigitCount(8);
    ui->systemTime->setText(QString(QTime::currentTime().toString("hh:mm:ss")));
    QTimer *timer = new QTimer(this);       //新建一个定时器
    connect(timer, &QTimer::timeout, this, &Widget::RefreshTime);
    timer->start(1000);     //以1000毫秒为周期
    ui->Transparency->setMinimum(0);
    ui->Transparency->setMaximum(255);
    ui->Transparency->setSingleStep(10);
    ui->Transparency->setValue(178);
    backgroundpath=QDir::homePath()+"/backgrounds";
    QString path=backgroundpath;
    QDir *dir=new QDir(path);
    QStringList filter;
    //filter<<"*.dat";
    //dir->setNameFilters(filter);
    QList<QFileInfo> *fileInfo=new QList<QFileInfo>(dir->entryInfoList(filter));
    Max=fileInfo->count()-2;
    ui->debug1->setText(QString::number(Max));
    ui->lineEdit->setText(backgroundpath);
    //ReadConfig();
    ui->stackedWidget->setCurrentIndex(0);
    this->setFocusPolicy(Qt::StrongFocus);
    Pic=QRandomGenerator().global()->bounded(1,18);
    refresh();
}

Widget::~Widget()
{
    delete ui;
}
/*void Widget::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event);

QPainter p(this);
p.drawPixmap(rect(),QPixmap(":/backgrounds/backgrounds/"+num+".jpg"),QRect());
}
*/
QString Widget::getTextFromYiYan()
{
    /*if (ui->OnlyShowPoems->isChecked())
    {
        curl->start("curl https://v1.hitokoto.cn/?c=i");
    }
    else
    {
        curl->start("curl https://v1.hitokoto.cn/");
    }
    curl->waitForFinished();
    QString YiYan=curl->readAllStandardOutput().simplified();
    */
    QUrl YiYan_url;
    QString text;
    if (ui->OnlyShowPoems->isChecked())
    {
        YiYan_url=QUrl("https://v1.hitokoto.cn/?c=i");
    }
    else
    {
        YiYan_url=QUrl("https://v1.hitokoto.cn/");
    }
    QNetworkAccessManager TextGeter;
    QEventLoop loop;
    QNetworkReply *reply;
    QNetworkRequest req;
    req=QNetworkRequest(YiYan_url);
    req.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
    reply = TextGeter.get(req);
    //完成后退出子事件循环
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    //开启子事件循环
    loop.exec();
    if (reply->error())
    {
        setAuther("无网络连接","");
        text="错误";
    }
    else
    {
    QString YiYan = reply->readAll();
    QStringList list = YiYan.split("\"");
    text=list[9];//获取正文
    QString from;
    QString from_Who;
    if (list[21]=="creator" || list[21]=="网络" || list[21]=="null")
    {
        if (list[17]=="网络" || list[17]=="热评" || list[17]=="原创")
        {
            from=list[17];
        }
        else
        {
            from="《"+list[17]+"》";
        }
        from_Who="";
    }
    else
    {
        from="《"+list[17]+"》";
        from_Who=list[21];
    }
    setAuther(from,from_Who);
    }
    return text;
}
void Widget::refresh()
{
    if (ui->PinText->isChecked())
    {
    }
    else
    {

        ui->YiYanText->setText("Loading...");
        ui->InformationLabel->setText("Loading...");
        ConcurrentIsFree=false;
        QtConcurrent::run([=](){
                ui->YiYanText->setText(getTextFromYiYan());
                ConcurrentIsFree=true;
        });
    //backgroundpath=ui->lineEdit->text();
    }
    if (ui->EnableDebugMode->isChecked())
    {
        ui->debug1->show();
        ui->debug2->show();
    }
    else
    {
        ui->debug1->hide();
        ui->debug2->hide();
    }
    if (ui->DarkText->isChecked())
    {
        ui->YiYanText->setStyleSheet("color: rgb(0, 0, 0);");
        ui->systemTime->setStyleSheet("color: rgb(0, 0, 0);");
        ui->lineEdit->setStyleSheet("background-color: rgba(255, 255, 255, 71);color: rgb(0,0,0);");
        ui->DarkText->setStyleSheet("color:rgb(0,0,0);");
        ui->OnlyShowPoems->setStyleSheet("color:rgb(0,0,0);");
        ui->EnableDebugMode->setStyleSheet("color:rgb(0,0,0);");
        ui->InformationLabel->setStyleSheet("color: rgb(30,30,30);");
        ui->PinText->setStyleSheet("color: rgb(0,0,0);");
        ui->PinWallpaper->setStyleSheet("color: rgb(0,0,0);");
        ui->getBackgroundFromOnline->setStyleSheet("color: rgb(0,0,0);");
        ui->exitBtn->setStyleSheet("color: rgb(30,30,30);");
        ui->refreshBtn->setStyleSheet("color: rgb(30,30,30);");
        ui->selectPathBtn->setStyleSheet("color: rgb(30,30,30);");
        ui->label->setStyleSheet("color: rgb(0, 0, 0);");
        ui->label_2->setStyleSheet("color: rgb(0, 0, 0);");
        ui->label_3->setStyleSheet("color: rgb(0, 0, 0);");
    }
    else
    {
        ui->YiYanText->setStyleSheet("color: rgb(255, 255, 255);");
        ui->systemTime->setStyleSheet("color: rgb(255, 255, 255);");
        ui->lineEdit->setStyleSheet("background-color: rgba(0,0,0,71);color: rgb(255, 255, 255);");
        ui->DarkText->setStyleSheet("color:rgb(255,255,255);");
        ui->OnlyShowPoems->setStyleSheet("color:rgb(255,255,255);");
        ui->EnableDebugMode->setStyleSheet("color:rgb(255,255,255);");
        ui->InformationLabel->setStyleSheet("color: rgb(200,200,200);");
        ui->PinText->setStyleSheet("color: rgb(255,255,255);");
        ui->PinWallpaper->setStyleSheet("color: rgb(255,255,255);");
        ui->getBackgroundFromOnline->setStyleSheet("color: rgb(255,255,255);");
        ui->exitBtn->setStyleSheet("color: rgb(200,200,200);");
        ui->refreshBtn->setStyleSheet("color: rgb(200,200,200);");
        ui->selectPathBtn->setStyleSheet("color: rgb(200,200,200);");
        ui->label->setStyleSheet("color: rgb(255,255,255);");
        ui->label_2->setStyleSheet("color: rgb(255,255,255);");
        ui->label_3->setStyleSheet("color: rgb(255,255,255);");
    }
    QFont font("思源黑体",16,75);
    QFont font2("思源黑体",10,63);
    QFont font3("思源黑体",12,50);
    QFont font4("Comfortaa",36,40);
    ui->YiYanText->setFont(font);
    ui->systemTime->setFont(font4);
    ui->refreshBtn->setFont(font2);
    ui->exitBtn->setFont(font2);
    ui->label->setFont(font3);
    ui->label_2->setFont(font3);
    ui->OnlyShowPoems->setFont(font3);
    ui->lineEdit->setFont(font3);
    ui->selectPathBtn->setFont(font3);
    ui->InformationLabel->setFont(font3);
    transparency=ui->Transparency->value();
    DrawBackground();
    //num=1;
    //getTextFromYiYan();
    //num=getRandNum();
    //QWidget::repaint();
}

void Widget::on_refreshBtn_clicked(bool checked)
{
    if (ConcurrentIsFree==true)
    {
        refresh();
    }
    else
    {
    }
}
QString Widget::getCurrentNum()
{
    /*int num=QRandomGenerator::global()->bounded(1,4);
    QString numToString=QString::number(num);
    return numToString;*/
    if (Pic<Max)
    {
        Pic++;
    }
    else
    {
        Pic=1;
    }
    ui->debug2->setText(QString::number(Pic));
    return QString::number(Pic);
}
void Widget::DrawBackground()
{
    if (ui->PinWallpaper->isChecked())
    {
        filling->setStyleSheet(QString("background-color: rgba(0,0,0,%1);").arg(ui->Transparency->value()));
    }
    else
    {
        num=getCurrentNum();
        if (ui->getBackgroundFromOnline->isChecked())
        {
            BgLabel->setScaledContents(true);
            BgLabel->resize(screenRect.width(),screenRect.height());
            //BgLabel->setPixmap(QPixmap().fromImage(currentWallpaper).scaled(BgLabel->size(),Qt::KeepAspectRatio, Qt::SmoothTransformation));
            BgLabel->setPixmap(DownloadPic());
        }
        else
        {
            currentWallpaper.load(backgroundpath+"/"+num+".jpg");
            BgLabel->setScaledContents(true);
            BgLabel->resize(screenRect.width(),screenRect.height());
            //BgLabel->setPixmap(QPixmap().fromImage(currentWallpaper).scaled(BgLabel->size(),Qt::KeepAspectRatio, Qt::SmoothTransformation));
            BgLabel->setPixmap(QPixmap().fromImage(currentWallpaper));
        }
        filling->resize(screenRect.width(),screenRect.height());
        filling->setStyleSheet(QString("background-color: rgba(0,0,0,%1);").arg(ui->Transparency->value()));
    }
    //BgLabel->show();
}
void Widget::keyPressEvent(QKeyEvent *event){
    if(event->key() == Qt::Key_R){
        if (ConcurrentIsFree==true)
        {
            refresh();
        }
        else
        {
        }
    }
    if(event->key() == Qt::Key_Escape){
        this->close();
    }
    if(event->key() == Qt::Key_S){
        ui->refreshBtn->show();
        ui->exitBtn->show();
    }
    if(event->key() == Qt::Key_H){
        ui->refreshBtn->hide();
        ui->exitBtn->hide();
    }
    if(event->key() == Qt::Key_P){
        if (ui->stackedWidget->currentIndex()==0)
        {
            ui->stackedWidget->setCurrentIndex(1);
        }
        else
        {
            if (ui->stackedWidget->currentIndex()==1)
            {
                ui->stackedWidget->setCurrentIndex(0);
            }
        }
    }
    if(event->key() == Qt::Key_E)
    {
        if (ui->getBackgroundFromOnline->isChecked())
        {
            SaveFile(ImageData);
        }
        else
        {

        }
    }
}
void Widget::setAuther(QString from, QString fromWho)
{
    if (from=="无网络连接")
    {
        ui->InformationLabel->setText(from);
    }
    else
    {
        ui->InformationLabel->setText("——"+fromWho+from);
    }
}
//void Widget::WriteConfig()
//{

//}

void Widget::on_selectPathBtn_clicked(bool checked)
{
    QString backgroundpathPreview=backgroundpath;
    backgroundpath=backgroundPath();
    if (backgroundpath=="")
    {
        ui->lineEdit->setText(backgroundpathPreview);
    }
    else
    {
        ui->lineEdit->setText(backgroundpath);
    }
}
QString Widget::backgroundPath()
{
    QString path=QFileDialog::getExistingDirectory(NULL, tr("选择文件夹"),QDir::homePath(),QFileDialog::ShowDirsOnly);
    QDir *dir=new QDir(path);
    QStringList filter;
    //filter<<"*.dat";
    //dir->setNameFilters(filter);
    QList<QFileInfo> *fileInfo=new QList<QFileInfo>(dir->entryInfoList(filter));
    Max=fileInfo->count()-2;
    ui->debug1->setText(QString::number(Max));
    Pic=1;
    return path;
}
QPixmap Widget::DownloadPic()
{
    QUrl Image_url;
    Image_url=QUrl("https://api.ixiaowai.cn/api/api.php");
    QNetworkAccessManager ImageGeter;
    QEventLoop loop;
    QNetworkReply *reply;
    QNetworkRequest req;
    req=QNetworkRequest(Image_url);
    req.setAttribute(QNetworkRequest::FollowRedirectsAttribute, true);
    reply = ImageGeter.get(req);
    //完成后退出子事件循环
    QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
    //开启子事件循环
    loop.exec();
    ImageData = reply->readAll();
    QPixmap getedImage;
    getedImage.loadFromData(ImageData);
    return getedImage;
}
void Widget::RefreshTime()
{
    ui->systemTime->setText(QString(QTime::currentTime().toString("hh:mm:ss")));
}
void Widget::SaveFile(QByteArray file)
{
    QFileDialog fileDialog;
    QString fileName = fileDialog.getSaveFileName(this,"Save to","");
    if(fileName == "")
    {
        return;
    }
    QFile savePic(fileName);
    if(!savePic.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        QMessageBox::warning(this,"呃～","你选择的是个什么奇奇怪怪的路径啊喂！");
        return;
    }
    else
    {
        savePic.write(file);
        savePic.close();
        QMessageBox::warning(this,"好耶！","下载完毕");
    }
}
